package com.zqxq.lottery.api.controller;

import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.api.feign.LotteryServerFeignClient;
import com.zqxq.lottery.common.constant.Constant;
import com.zqxq.lottery.common.utils.CommonUtil;
import com.zqxq.lottery.common.utils.JsonUtils;
import com.zqxq.lottery.entity.po.analysis.AnalysisMatchPO;
import com.zqxq.lottery.entity.po.jczq.JczqMatchLivePO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "赛事分析接口",tags = "赛事分析接口")
@RestController
@Slf4j
@RequestMapping(value = "/analysis", produces = "application/json")
public class AnalysisController {

    @Autowired
    private LotteryServerFeignClient lotteryServerFeignClient;

    /**
     * 作者:    
     * 创建时间: 2018年7月24日上午10:26:38
     * 描述:    赛事分析-比賽事件查询
     * 备注:
     * throw_ins：
     * dangerous_attacks：有威胁攻势
     * attacks：
     * corners：角球
     * free_kicks：任意球
     * fouls：犯规
     * shots_blocked：被封堵
     * shots_off_target：射偏
     * goals：越位
     * yellow cards：黄牌
     * shots_on_target：射正
     * goal_kicks：
     * shots_woodwork：
     * substitutions：
     * offsides：
     * team_h_data:主队
     * team_a_data:客队
     *
     * @param code 赛事编号
     * @return
     */
    @ApiOperation("赛事分析-比賽事件查询")
    @PostMapping("/getAnalysisEvent")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "賽事编号", paramType = "query", dataType = "String", required = true, defaultValue = "109103")
    })
    public Result getAnalysisEvent(String code) {
        if (CommonUtil.isEmpty(code)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "賽事编号不能为空");
        }
        Result result = lotteryServerFeignClient.getAnalysisEvent(code);
        //json字符串对象转化
        if (CommonUtil.isNotEmpty(result) && CommonUtil.isNotEmpty(result.getData()) && result.success()) {
            List<Map<String, Object>> data = (List<Map<String, Object>>) result.getData();
            for (Map<String, Object> po : data) {
                if (CommonUtil.isNotEmpty(po.get("event_result"))) {
                    if (Integer.valueOf(po.get("event_type").toString()) == Constant.EVENT_TYPE_0) {
                        po.put("event_result", JsonUtils.jsonToTwoDimensionalMap(po.get("event_result").toString()));
                    } else {
                        po.put("event_result", JsonUtils.jsonToMap(po.get("event_result").toString()));
                    }
                }else{
                    if (Integer.valueOf(po.get("event_type").toString()) == Constant.EVENT_TYPE_0) {
                        po.put("event_result", new ArrayList<Map<String, Object>>());
                    } else {
                        po.put("event_result", new HashMap<String, Object>());
                    }
                }
            }
        }
        return result;
    }

    /**
     * 作者:    
     * 创建时间: 2018年7月24日上午10:26:38
     * 描述:    赛事分析-比賽首发阵容查询
     * 备注:
     *
     * @param code 赛事编号
     * @return
     */
    @ApiOperation("赛事分析-比賽首发阵容查询")
    @PostMapping("/getAnalysisLineup")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "賽事编号", paramType = "query", dataType = "String", required = true, defaultValue = "109003")
    })
    public Result getAnalysisLineup(String code) {
        if (CommonUtil.isEmpty(code)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "賽事编号不能为空");
        }
        Result result = lotteryServerFeignClient.getAnalysisLineup(code);
        //json字符串对象转化
        if (CommonUtil.isNotEmpty(result) && CommonUtil.isNotEmpty(result.getData()) && result.success()) {
            List<Map<String, Object>> data = (List<Map<String, Object>>) result.getData();
            for (Map<String, Object> po : data) {
                if (CommonUtil.isNotEmpty(po.get("host_result"))) {
                    po.put("host_result", JsonUtils.jsonToListMap(po.get("host_result").toString()));
                }else{
                    po.put("host_result", new ArrayList<Map<String, Object>>());
                }
                if (CommonUtil.isNotEmpty(po.get("guest_result"))) {
                    po.put("guest_result", JsonUtils.jsonToListMap(po.get("guest_result").toString()));
                }else{
                    po.put("guest_result", new ArrayList<Map<String, Object>>());
                }
            }
        }
        return result;
    }

    /**
     * 作者:    
     * 创建时间: 2018年7月24日上午10:26:38
     * 描述:    赛事分析-比賽预测信息查询
     * 备注:
     *
     * @param code 赛事编号
     * @return
     */
    @ApiOperation("赛事分析-比賽预测信息查询")
    @PostMapping("/getAnalysisForecast")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "賽事编号", paramType = "query", dataType = "String", required = true, defaultValue = "109099")
    })
    public Result getAnalysisForecast(String code) {
        if (CommonUtil.isEmpty(code)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "賽事编号不能为空");
        }
        Result result = lotteryServerFeignClient.getAnalysisForecast(code);
        //json字符串对象转化
        jsonToMap(result, "spf_forecast", "rqspf_forecast");
        Map<String, Object> map = null;
        if (CommonUtil.isNotEmpty(result) && CommonUtil.isNotEmpty(result.getData()) && result.success()) {
            map = (Map<String, Object>) result.getData();
            if (CommonUtil.isNotEmpty(map)) {
                Result<JczqMatchLivePO> match = lotteryServerFeignClient.getAnalysisMatch(code);
                if (CommonUtil.isNotEmpty(match) && CommonUtil.isNotEmpty(match.getData()) && match.success()) {
                    map.put("goal_line", match.getData().getGoal_line());
                } else {
                    map.put("goal_line", null);
                }

            }
        }
        return new Result<>(result.getCode(), result.getMsg(), CommonUtil.isEmpty(map) ? null : map);
    }

    /**
     * 作者:    
     * 创建时间: 2018年7月24日上午10:26:38
     * 描述:    赛事分析-头部数据
     * 备注:
     *
     * @param code 赛事编号
     * @return
     */
    @ApiOperation("赛事分析-头部数据")
    @PostMapping("/getAnalysisMatch")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "賽事编号", paramType = "query", dataType = "String", required = true)
    })
    public Result<AnalysisMatchPO> getAnalysisMatch(String code) {
        if (CommonUtil.isEmpty(code)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "賽事编号不能为空");
        }
        Result<JczqMatchLivePO> result = lotteryServerFeignClient.getAnalysisMatch(code);
        return new Result(result.getCode(), result.getMsg(), CommonUtil.isEmpty(result.getData()) ? null : result.getData());
    }

    /**
     * 作者:    
     * 创建时间: 2018年7月23日下午16:09:38
     * 描述:    赛事分析-赔率信息查询
     * 备注:"""解析欧赔数据
     * <p>
     * 数据来源: http://i.sporttery.cn/api/fb_match_info/get_europe/?f_callback=hb_odds&mid=[赛事id]&_=[时间戳]
     * 返回结果部分参数说明:
     * ========= Total ===========
     * win_s_max: 初始奖金-胜-最大值
     * win_s_avg: 初始奖金-胜-平均值
     * win_s_min: 初始奖金-胜-最小值
     * ---------------------------
     * draw_s_max: 初始奖金-平-最大值
     * draw_s_avg: 初始奖金-平-平均值
     * draw_s_min: 初始奖金-平-最小值
     * ---------------------------
     * lose_s_max: 初始奖金-负-最大值
     * lose_s_avg: 初始奖金-负-平均值
     * lose_s_min: 初始奖金-负-最小值
     * ---------------------------
     * win_max: 即时奖金-胜-最大值
     * win_avg: 即时奖金-胜-平均值
     * win_min: 即时奖金-胜-最小值
     * ---------------------------
     * draw_max: 即时奖金-平-最大值
     * draw_avg: 即时奖金-平-平均值
     * draw_min: 即时奖金-平-最小值
     * ---------------------------
     * lose_max: 即时奖金-负-最大值
     * lose_avg: 即时奖金-负-平均值
     * lose_min: 即时奖金-负-最小值
     * =========== data ==============
     * cn: 公司
     * win_s: 初始奖金-胜
     * draw_s: 初始奖金-平
     * lose_s: 初始奖金-负
     * win: 即时奖金-胜
     * draw: 即时奖金-平
     * lose: 即时奖金-负
     * win_s_index: 凯利指数-初始-胜
     * draw_s_index: 凯利指数-初始-平
     * lose_s_index: 凯利指数-初始-负
     * win_index: 凯利指数-即时-胜
     * draw_index: 凯利指数-即时—平
     * lose_index: 凯利指数-即时-负
     * ==============================
     * <p>
     * Args:
     * response: 返回数据
     * <p>
     * Returns:
     * item 'odds_result' 字段同请求返回结果中的 'data'
     * """"""解析亚盘数据
     * <p>
     * 数据来源: http://i.sporttery.cn/api/fb_match_info/get_europe/?f_callback=asia_tb&mid=[赛事id]&_=[时间戳]
     * 返回结果部分参数说明:
     * cn: 公司
     * o1_s: 初盘-主水
     * o3_s: 初盘-盘口
     * o2_s: 初盘-客水
     * o1: 即时盘-主水
     * o3: 即时盘-盘口
     * o2: 即时盘-客水
     * <p>
     * Args:
     * response: 返回数据
     * <p>
     * Returns:
     * item 'odds_result' 字段同请求返回结果
     * """
     *
     * @param code      赛事编号
     * @param odds_type 赔率类型(0-亚盘,1-欧赔,2-大小球)"
     * @return
     */
    @ApiOperation("赛事分析-赔率信息查询")
    @PostMapping("/getAnalysisOdds")
    public Result getAnalysisOdds(@ApiParam(value = "賽事编号", required = true, defaultValue = "108945") @RequestParam() String code,
                                  @ApiParam(value = "赔率类型(0-亚盘,1-欧赔,2-大小球)", required = true) @RequestParam() Integer odds_type) {
        if (CommonUtil.isEmpty(code)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "賽事编号不能为空");
        }
        if (CommonUtil.isEmpty(odds_type)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "赔率类型不能为空");
        }
        Result result = lotteryServerFeignClient.getAnalysisOdds(code, odds_type);
        //json字符串对象转化
        jsonToListMap(result, "odds_result");
        return result;
    }

    /**
     * 作者:    
     * 创建时间: 2018年7月24日上午10:26:38
     * 描述:    赛事分析-比賽积分信息查询
     * 备注:
     *
     * @param code  赛事编号
     * @param point_type 积分类型 0-总积分；1-主场积分；2-客场积分
     * @return
     */
    @ApiOperation("赛事分析-比賽积分信息查询")
    @PostMapping("/getAnalysisPoint")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "賽事编号", paramType = "query", dataType = "String", required = true, defaultValue = "109104"),
            @ApiImplicitParam(name = "point_type", value = "积分类型 0-总积分；1-主场积分；2-客场积分", paramType = "query", dataType = "Integer", required = true)
    })
    public Result getAnalysisPoint(String code, Integer point_type) {
        if (CommonUtil.isEmpty(point_type)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "积分类型不能为空");
        }
        if (CommonUtil.isEmpty(code)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "賽事编号不能为空");
        }
        Result result = lotteryServerFeignClient.getAnalysisPoint(code, point_type);
        //json字符串对象转化
        jsonToListMap(result, "point_result");
        Map<String, Object> params = new HashMap<>();
        if (CommonUtil.isNotEmpty(result) && CommonUtil.isNotEmpty(result.getData()) && result.success()) {
            Result<JczqMatchLivePO> match = lotteryServerFeignClient.getAnalysisMatch(code);
            params.put("point", result.getData());
            if (CommonUtil.isNotEmpty(match) && CommonUtil.isNotEmpty(match.getData()) && match.success()) {
                params.put("name", match.getData().getLeague());
            } else {
                params.put("name", null);
            }
        } else {
            params.put("point", null);
            params.put("name", null);
        }
        result.setData(params);
        return result;
    }

    /**
     * 作者:    
     * 创建时间: 2018年7月23日下午16:09:38
     * 描述:    赛事分析-分析(比賽历史交锋，近期战绩，未来赛事)查询
     * 备注:
     *
     * @param code    赛事编号
     * @param user_id 用户编号
     * @return
     */
    @ApiOperation("赛事分析-分析(比賽历史交锋，近期战绩，未来赛事)查询")
    @PostMapping("/getAnalysisRecord")
    public Result<?> getAnalysisRecord(@ApiParam(value = "用户Id", required = false, defaultValue = "100101") @RequestParam(value = "user_id", required = false) Long user_id,
                                       @ApiParam(value = "賽事编号", required = true, defaultValue = "109107") @RequestParam("code") String code) {
        if (CommonUtil.isEmpty(code)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "賽事编号不能为空");
        }
        Result result = lotteryServerFeignClient.getAnalysisRecord(code, user_id);
        //json字符串对象转化
        if (CommonUtil.isNotEmpty(result) && CommonUtil.isNotEmpty(result.getData()) && result.success()) {
            Map<String, Object> data = (Map<String, Object>) result.getData();
            //比賽历史交锋，近期战绩，未来赛事
            List<Map<String, Object>> recordPOList = (List<Map<String, Object>>) data.get("recordPOList");
            if (CommonUtil.isNotEmpty(recordPOList)) {
                for (Map<String, Object> po : recordPOList) {
                    //简要结果
                    if (CommonUtil.isNotEmpty(po.get("record_simple_result"))) {
                        po.put("record_simple_result", JsonUtils.jsonToMap(po.get("record_simple_result").toString()));
                    } else {
                        po.put("record_simple_result", null);
                    }
                    //具体结果
                    if (CommonUtil.isNotEmpty(po.get("record_detail_result"))) {
                        List<Map<String,Object>> res = JsonUtils.jsonToListMap(po.get("record_detail_result").toString());
                        List<Map<String,Object>> rus = new ArrayList<>();
                        if(CommonUtil.isNotEmpty(res) && (Integer.valueOf(po.get("record_type").toString()) == Constant.RECORD_TYPE_0 || Integer.valueOf(po.get("record_type").toString()) == Constant.RECORD_TYPE_1 || Integer.valueOf(po.get("record_type").toString()) == Constant.RECORD_TYPE_3)){
                            for (Map<String,Object> map:res){
                                if(CommonUtil.isNotEmpty(map.get("result"))){
                                    rus.add(map);
                                }
                            }
                        }
                        if(Integer.valueOf(po.get("record_type").toString()) == Constant.RECORD_TYPE_0 || Integer.valueOf(po.get("record_type").toString()) == Constant.RECORD_TYPE_1 || Integer.valueOf(po.get("record_type").toString()) == Constant.RECORD_TYPE_3){
                            po.put("record_detail_result", rus);
                        }else {
                            po.put("record_detail_result", res);
                        }
                    } else {
                        po.put("record_detail_result", null);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 作者:    
     * 创建时间: 2018年7月23日下午16:09:38
     * 描述:    赛事分析-分析-投票
     * 备注:
     *
     * @param code      赛事编号
     * @param user_id   用户编号
     * @param vote_type 投票类型 0-主胜；1-平；3-客胜；
     * @return
     */
    @ApiOperation("赛事分析-分析-投票")
    @PostMapping("/addAnalysisVote")
    public Result addAnalysisVote(@ApiParam(value = "用户Id", required = true, defaultValue = "100101") @RequestParam() Long user_id,
                                  @ApiParam(value = "賽事编号", required = true, defaultValue = "109029") @RequestParam() String code,
                                  @ApiParam(value = "投票类型(0-主胜,1-平,3-客胜；)", required = true) @RequestParam() Integer vote_type) {
        if (CommonUtil.isEmpty(user_id) || user_id.intValue() == 0) {
            return new Result<>(CodeEnum.FAIL.getCode(), "用户编号不能为空");
        }
        if (CommonUtil.isEmpty(code)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "賽事编号不能为空");
        }
        if (CommonUtil.isEmpty(vote_type)) {
            return new Result<>(CodeEnum.FAIL.getCode(), "投票类型不能为空");
        }
        return lotteryServerFeignClient.addAnalysisVote(code, user_id, vote_type);
    }

    /**
     * json转换
     *
     * @param result
     * @param tranName
     */
    private void jsonToListMap(Result result, String tranName) {
        if (CommonUtil.isNotEmpty(result) && CommonUtil.isNotEmpty(result.getData()) && result.success()) {
            List<Map<String, Object>> data = (List<Map<String, Object>>) result.getData();
            for (Map<String, Object> po : data) {
                if (CommonUtil.isNotEmpty(po.get(tranName))) {
                    po.put(tranName, JsonUtils.jsonToListMap(po.get(tranName).toString()));
                }
            }
        }
    }

    private void jsonToMap(Result result, String tranNameOne, String tranNameTwo) {
        if (CommonUtil.isNotEmpty(result) && CommonUtil.isNotEmpty(result.getData()) && result.success()) {
            Map<String, Object> po = (Map<String, Object>) result.getData();
            if (CommonUtil.isNotEmpty(tranNameOne)) {
                if (CommonUtil.isNotEmpty(po.get(tranNameOne))) {
                    po.put(tranNameOne, JsonUtils.jsonToMap(po.get(tranNameOne).toString()));
                }
            }
            if (CommonUtil.isNotEmpty(tranNameTwo)) {
                if (CommonUtil.isNotEmpty(po.get(tranNameTwo))) {
                    po.put(tranNameTwo, JsonUtils.jsonToMap(po.get(tranNameTwo).toString()));
                }
            }
        }
    }
}
